#version 430
in vec4 vcolor;
out vec4 fragColor;
in vec2 vary_uv;



const float R0 = 6360e3; // Earth surface radius
const float Ra = 6380e3; // Earth atmosphere top raduis
const vec3 C = vec3(0., 0, 0.); // Earth center point

vec3 sundir = normalize(vec3(0.5, 0.4, -1.0));

vec3 eyePosi = vec3(0.0, R0 + 10.0, 0.0);

const vec3 bR = vec3(58e-7, 135e-7, 331e-7); // Rayleigh scattering coefficient
const vec3 bMs = vec3(2e-5); // Mie scattering coefficients
const vec3 bMe = bMs * 1.1;
vec2 totalDensity = vec2(0.0);

const int STEPS0 = 16;
const int STEPS1 = 4;

// vDir is uniform vector;
// return vec2(inL, outL) ;
vec2 ray2sphere(vec3 vStart, vec3 vDir, vec3 vEC, float radius) {
	vec3 vL = vEC - vStart;
	float a1 = dot(vL, vDir);
	float l = length(vL);
	float hh = l * l - a1 * a1;
	float h = sqrt(hh);
	if (h > radius) return vec2(-1.0, -1.0);
	float a2 = sqrt(radius * radius - hh);
	float inL = a1 - a2;
	float outL = a1 + a2;
	return vec2(inL, outL);
}

// re : radius of earth
// ratm : radius of atmosphere
vec2 ray2atmosphere(vec3 vStart, vec3 vDir, vec3 vEC, float re, float ratm) {
	vec2 lla = ray2sphere(vStart, vDir, vEC , ratm);
	vec2 lle = ray2sphere(vStart, vDir, vEC , re  );

	if (lla.x < 0 && lla.y < 0) {
		//outside atm
		return lla;
	} else if (lle.x < 0 && lle.y < 0) {
		//no inter ground
		lla.x = max(0.0, lla.x);
		return lla; //suppose lla.y must greater than 0.
	} else {
		//inter atm and ground
		float lnear = max(0.0, min(lla.x, lle.x));
		float lfar = lle.x;
		return vec2(lnear, lfar);
	}
}


void main()
{
    vec2 uv = vary_uv;
    uv.x = vary_uv.x * 8.0 / 6.0;
	vec3 vDir = normalize(vec3(uv.xy, -1.0));

	vec3 vStart = vec3(0.0, 0.0, 15.0);
	vec3 vEC = vec3(0.0);
	float ra = 10.0;
	float re = 8.0;

	vec2 nearFarL = ray2atmosphere(vStart, vDir, vEC, re, ra);
	fragColor = vec4(0.0, 0.0, (nearFarL.y - nearFarL.x) / 10.0, 1.0);

	
}